import * as echarts from '../../../ec-canvas/echarts';
import http from '../../../http/http.js'

function createOption(data) {
  console.log("11" + data.categoryData)
  return {
    // tooltip: {
    //   trigger: 'axis',
    //   axisPointer: {
    //     type: 'shadow'
    //   }
    // },
    grid: {
      bottom: 90
    },
    // dataZoom: [{
    //   type: 'inside'
    // }, {
    //   type: 'slider'
    // }],
    xAxis: {
      data: data.categoryData,
      silent: false,
      splitLine: {
        show: false
      },
      splitArea: {
        show: false
      },
      axisLabel: {
        fontSize: 14,
        rich: {}
      },
    },
    yAxis: {
      splitArea: {
        show: false
      },
      axisLabel: {
        fontSize: 14,
        rich: {}
      },
    },
    series: [{
      type: 'line',
      data: data.valueData,
      large: true,
      label: {
        normal: {
          fontSize: 14,
          rich: {}
        }
      },
      lineStyle: {
        color: '#39B789',
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: '#39B789'
        }, {
          offset: 1,
          color: '#ffffff'
        }])
      },
    }]
  };
}

function formatChartValue(datas) {
  let result = {
    categoryData: [],
    valueData: []
  };

  datas.forEach(item => {
    result.categoryData.push(item.time);
    result.valueData.push(item.value/1000);
  });

  console.log(result);

  return result;
}

// NOTE: 这里有点问题，在页面注销的时候，需要清除一下chartInstance；
const chartInstance = {};


function initChart(chartType) {
  return function(canvas, width, height) {
    chartInstance[chartType] = echarts.init(canvas, null, {
      width: width,
      height: height
    });
    canvas.setChart(chartInstance[chartType]);
    // 初始化默认为空
    const option = createOption({
      categoryData: [],
      valueData: [],
    });

    chartInstance[chartType].setOption(option);
    return chartInstance[chartType];
  }
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    fx: true,
    yj: false,
    read: true,
    readed: false,
    deviceCode: '',
    beeboxinfo: '',
    temperatureEc: {
      onInit: initChart('temperatureChart'),
    },
    weightEc: {
      onInit: initChart('weightChart'),
    },
    passHiveNumberEc: {
      onInit: initChart('passHiveNumberChart'),
    },
    humidityEc: {
      onInit: initChart('humidityChart'),
    },
    soundEc:{
      onInit: initChart('soundChart'),
    },
    weight: [],
    humidity: [],
    temperature: [],
    passHiveNumber: [],
    sound:[],
    notred: {},
    hasred: {},
    alertpop: false,
    hiveid:''
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    this.getbeeboxinfo(this.data.deviceCode)
  },
  onLoad: function(options) {
    let deviceCode = options.deviceCode
    this.setData({
      deviceCode: deviceCode,
    })

    this.getbeeboxinfo(deviceCode)
  },
  onShow: function() {
    this.getbeeboxinfo(this.data.deviceCode)
    
    this.timer = setInterval(() => {
      this.getwarmlist(this.data.hiveid)
      this.getwarmedlist(this.data.hiveid)
    }, 300000); 
  },
  onHide: function () {
    clearInterval(this.timer);
  },
  onUnload: function () {
    clearInterval(this.timer);
  }, 
  // 获取预警未读
  getwarmlist: function(arg) {
    http.getdata('/api/monitor/list?status=1&hiveId=' + arg).then((res) => {
      this.setData({
        notred: res.data.result
      })
    })
  },
  //获取预警已读
  getwarmedlist: function(arg) {
    http.getdata('/api/monitor/list?status=3&hiveId=' + arg).then((res) => {
      this.setData({
        hasred: res.data.result
      })
    })
  },
  // 获取蜂箱信息
  getbeeboxinfo: function(arg) {
    http.getdata('/api/beehive/get?deviceCode=' + arg).then((res) => {
      this.setData({
        hiveid: res.data.result.hiveId,
        beeboxinfo: res.data.result,
        id: res.data.result.id,
        talkOfficeTime: res.data.result.talkOfficeTime ? res.data.result.talkOfficeTime.split(' ')[0] : ''
      })
      this.getwarmlist(res.data.result.hiveId)
      this.getwarmedlist(res.data.result.hiveId)
      this.getTimeLineData(res.data.result.hiveId)
    })
    wx.stopPullDownRefresh()
  },
  getTimeLineData: function(hiveId) {
    let curTime = Date.now();
    let startTime = curTime - (60 * 60 * 24 * 1000);
    http.getdata(`/api/beehive/ts/get?hiveId=${hiveId}&startTime=${startTime}&endTime=${curTime}`).then((res) => {
      const {
        data: {
          result
        }
      } = res;
      let {
        passHiveNumber = [], temperature = [], humidity = [], weight = [], sound=[
          { time: "00:01:48", value: 10 },
          { time: "00:01:48", value: 20 },
          
        ]
      } = result;

      weight = formatChartValue(weight);
      humidity = formatChartValue(humidity);
      passHiveNumber = formatChartValue(passHiveNumber);
      temperature = formatChartValue(temperature);
      sound = formatChartValue(sound);

      chartInstance.weightChart.setOption(createOption(weight))
      chartInstance.humidityChart.setOption(createOption(humidity))
      chartInstance.passHiveNumberChart.setOption(createOption(passHiveNumber))
      chartInstance.temperatureChart.setOption(createOption(temperature))
      chartInstance.soundChart.setOption(createOption(sound))

      this.setData({
        weight,
        humidity,
        temperature,
        passHiveNumber,
        sound
      })
    })
  },
  fx_tab: function() {
    this.setData({
      fx: true,
      yj: false,
    })
  },
  yj_tab: function() {
    this.setData({
      fx: false,
      yj: true,
    })
  },
  yj_tab_in: function(e) {
    let val = e.currentTarget.dataset.val
    if (val == '1') {
      this.setData({
        read: true,
        readed: false,
      })
    } else {
      this.setData({
        read: false,
        readed: true,
      })
    }
  },
  to_edit: function() {
    wx.navigateTo({
      url: '../edit/edit?deviceCode=' + this.data.deviceCode + '&id=' + this.data.id,
    })
  },
  viewbee: function(e) {
    let ids = e.currentTarget.dataset.id
    let message = e.currentTarget.dataset.message
    let beeid = e.currentTarget.dataset.beeid
    this.setData({
      alertpop: true,
      popmes: message,
      id: ids,
      beeid: beeid
    })
  },
  // 关闭查看
  closepop: function() {
    let pars = {
      id: this.data.id
    }
    http.putdata('/api/monitor/process', pars).then((res) => {
      this.setData({
        alertpop: false
      })
      http.getdata('/api/monitor/list?status=1&apiaryId=' + this.data.beeid).then((res) => {
        this.setData({
          notred: res.data.result,
        })
      })
    })
  }
})
